/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package brisollogic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *This class handles communication with the db.
 * @author Alex
 */
public enum DAL implements DatabaseConnection {

    INSTANCE;
    private static final String SQL_CONNECTION_URL = "jdbc:sqlserver://127.0.0.1;instanceName=sqlexpress;";
    private static final String SQL_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static final String SQL_USER = "sa";
    private static final String SQL_PASSWORD = "Pa$$w0rd";
    private static boolean isDriverLoaded = false;

    /**
     * creates a connection for the database
     * @return Connection
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    @Override
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Connection con = null;
        try {
            if (!isDriverLoaded) {
                loadDriver();
            }

            con = DriverManager.getConnection(SQL_CONNECTION_URL, SQL_USER, SQL_PASSWORD);
        } catch (SQLException e) {
            throw e;
        } catch (ClassNotFoundException e) {
            loadDriver();
        }
        return con;
    }

    private void loadDriver() throws ClassNotFoundException {
        try {
            Class.forName(SQL_DRIVER);
            isDriverLoaded = true;
        } catch (ClassNotFoundException e) {
            throw new ClassNotFoundException("Driver ikke loaded", e);
        }

    }
    
    @Override
    public String toString() {
        return ("SQL CONNECTION URL " + SQL_CONNECTION_URL + "\n  Driver Loaded " + isDriverLoaded);
    }
}
